package com.yunkeji.api.auth.processor.login;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yunkeji.api.auth.bo.ToLoginBo;
import com.yunkeji.api.auth.processor.service.LoginFactory;
import com.yunkeji.api.auth.processor.service.LoginStrategy;
import com.yunkeji.api.auth.service.AuthService;
import com.yunkeji.api.auth.vo.ToLoginVo;
import com.yunkeji.common.constant.CacheConstants;
import com.yunkeji.common.enums.app.AppUserStatus;
import com.yunkeji.common.exception.AppServiceException;
import com.yunkeji.common.utils.redis.RedisUtils;
import com.yunkeji.dao.domain.AppUser;
import com.yunkeji.dao.mapper.AppUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 密码登录
 *
 * @author 老张
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PasswordLogin implements InitializingBean, LoginStrategy {
    private final AuthService authService;
    private final AppUserMapper appUserMapper;
    private static String EVN = SpringUtil.getActiveProfile();

    @Override
    public ToLoginVo execute(ToLoginBo bo) {
        AppUser appUser =
                appUserMapper.selectOne(
                        Wrappers.lambdaQuery(AppUser.class)
                                //  .eq(AppUser::getPassword, BCrypt.hashpw(bo.getPassword()))
                                .ne(AppUser::getStatus, AppUserStatus.永久删除.getCode())
                                .eq(AppUser::getPhone, bo.getPhone()));
        if (appUser == null || !BCrypt.checkpw(bo.getPassword(), appUser.getPassword())) {
            Boolean aBoolean =
                    RedisUtils.setAtomicValueAdd(
                            CacheConstants.LOGIN_LIMIT + bo.getPhone(), 10, 24 * 60 * 60);
            if (!aBoolean) {
                throw AppServiceException.paramException("账号已被锁定,请24小时后再试.");
            }
            throw AppServiceException.paramException("账号不存在或密码错误");
        }
        return authService.toLogin(bo, false);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        LoginFactory.put(ToLoginBo.LoginType.密码登录, this);
    }
}
